package models;

import java.util.List;

import javax.persistence.Entity;

import jiyici.Constant.ModelColumn;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;

import play.db.ebean.Model;

@Entity
public class Item extends ServerBaseModel {

    private static final long serialVersionUID = -9073219935291887960L;

    public String itemName;

    public long categoryId;

    public String displayIndex;

    public int recordCount;

    // @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.PERSIST,
    // CascadeType.MERGE, CascadeType.REMOVE }, mappedBy = "item")
    // public List<ItemParam> params = new ArrayList<ItemParam>();

    @Override
    public ObjectNode toJson() {
        ObjectNode node = super.toJson();
        node.put(ModelColumn.ITEM_COLUMN_NAME, itemName);
        node.put(ModelColumn.ITEM_COLUMN_CATEGORYID, categoryId);
        node.put(ModelColumn.ITEM_COLUMN_DISPLAY_INDEX, displayIndex);
        node.put(ModelColumn.ITEM_COLUMN_RECORD_COUNT, recordCount);
        return node;
    }

    @Override
    public void fromJson(JsonNode json) {
        super.fromJson(json);
        itemName = json.findPath(ModelColumn.ITEM_COLUMN_NAME).getTextValue();
        categoryId = json.findPath(ModelColumn.ITEM_COLUMN_CATEGORYID).getLongValue();
        displayIndex = json.findPath(ModelColumn.ITEM_COLUMN_DISPLAY_INDEX).getTextValue();
        recordCount = json.findPath(ModelColumn.ITEM_COLUMN_RECORD_COUNT).getIntValue();
    }

    public static Model.Finder<Long, Item> find = new Model.Finder<Long, Item>(Long.class, Item.class);

    public static List<Item> modifiedAfter(User user, long time) {
        return find.where().eq("modelId.userId", user.id).gt(ModelColumn.BASE_COLUMN_LASTMODIFIED, time)
                .findList();
    }

    public static Item addItem(User user, String name, long category, ItemParam[] paramArray) {
        // Item item = new Item();
        // item.userId = user.id;
        // item.itemName = name;
        // item.categoryId = category;
        // item.displayIndex = 0; /* TODO display index */
        // item.recordCount = 0;
        // int size = paramArray.length;
        // for (int i = 0; i < size; i++) {
        // item.params.add(paramArray[i]);
        // }
        // item.save();
        // return item;
        return null;
    }

    public static List<Item> findByUser(User user) {
        return find.where().eq("userId", user.id).findList();
    }
}
